package pers.qianyu.month_202101.date_20210119;

import org.junit.*;

import java.util.*;

/**
 * 227. 基本计算器 II
 * https://leetcode-cn.com/problems/basic-calculator-ii/
 *
 * @author mizzle rain
 * @date 2021-01-19 19:32
 */
public class Calculate {
    public int calculate(String s) {
        Deque<Integer> st = new LinkedList<>();
        s = s.trim();
        int len = s.length();
        if (len == 0) return 0;
        char op = '+';
        for (int i = 0; i < len; i++) {
            char ch = s.charAt(i);
            if (ch == ' ') continue;
            if (Character.isDigit(ch)) {
                int sum = ch - '0';
                i++;
                while (i < len && Character.isDigit(s.charAt(i))) {
                    sum = sum * 10 + (s.charAt(i) - '0');
                    i++;
                }
                if (op == '+') st.push(sum);
                else if (op == '-') st.push(-sum);
                else st.push(compute(op, st.poll(), sum));
                i--;
            } else {
                op = ch;
            }
        }
        int res = 0;
        for (int i : st) res += i;
        return res;
    }

    private int compute(char op, int a, int b) {
        if (op == '+') {
            return a + b;
        } else if (op == '-') {
            return a - b;
        } else if (op == '*') {
            return a * b;
        } else {
            return a / b;
        }
    }

    @Test
    public void test1() {
        int result = new Calculate().calculate(" 3+5 / 2 ");
        System.out.println("result = " + result);
    }
}
